package com.example.booksdeal.basic;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.booksdeal.R;
import com.example.booksdeal.adapter.Adapter_ChatMessage;
import com.example.booksdeal.modle.ChatMessage;
import com.example.booksdeal.util.DBOpenHelper;

import java.util.ArrayList;
import java.util.List;


public class ChatActivity extends AppCompatActivity implements View.OnClickListener {

    private Context mContext;
    private EditText et_content;
    private ListView listView;
    private Button btn_send;
    private String gid,mConversation;
    private List<ChatMessage> chatMessageList = new ArrayList<>();//消息列表
    private Adapter_ChatMessage adapter_chatMessage;
    // 消息监听器
//    private EMMessageListener mMessageListener;
    private DBOpenHelper dbOpenHelper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_chat);
        dbOpenHelper = new DBOpenHelper(this,"db_booksdeal.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        db = dbOpenHelper.getWritableDatabase();
        Bundle bundle = this.getIntent().getExtras();
        gid = bundle.getString("gid");
        mContext = ChatActivity.this;
//        mMessageListener = this;
        findViewById();
        initView();
    }

    private void findViewById() {
        listView = findViewById(R.id.chatmsg_listView);
        btn_send = findViewById(R.id.btn_send);
        et_content = findViewById(R.id.et_content);
        btn_send.setOnClickListener(this);
    }

    private void initView() {
        //监听输入框的变化
        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (et_content.getText().toString().length() > 0) {
                    btn_send.setVisibility(View.VISIBLE);
                } else {
                    btn_send.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        Cursor cursor = db.query("BooksDetail",new String[]{"username"}, "id=?",new String[]{gid},null,null,null);
        if (cursor != null && cursor.getCount() > 0){
            while (cursor.moveToNext()){
                mConversation = cursor.getString(cursor.getColumnIndex("username"));
                }
            }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                String content = et_content.getText().toString();
                if (content.length() <= 0) {
                    Toast.makeText(mContext, "消息不能为空哟", Toast.LENGTH_LONG);
                    return;
                }
                //暂时将发送的消息加入消息列表，实际以发送成功为准（也就是服务器返回你发的消息时）
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setContent(content);
                chatMessage.setIsMeSend(1);
                chatMessage.setIsRead(1);
                chatMessage.setTime(System.currentTimeMillis() + "");
                chatMessageList.add(chatMessage);
                sendMessage(content);
                et_content.setText("");
                initChatMsgListView();
                break;
            default:
                break;
        }
    }

    /**
     * 发送消息
     */
    private void sendMessage(String messageStr){
//        EMMessage messagelay = EMMessage.createTxtSendMessage(messageStr,mConversation);
//        EMClient.getInstance().chatManager().sendMessage(messagelay);
    }

    // 更新界面ui
    private void initChatMsgListView(){
        adapter_chatMessage = new Adapter_ChatMessage(mContext, chatMessageList);
        listView.setAdapter(adapter_chatMessage);
        listView.setSelection(chatMessageList.size());
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 添加消息监听
//        EMClient.getInstance().chatManager().addMessageListener(mMessageListener);
    }

        /**
     * 接收消息
     */
//    @Override
//    public void onMessageReceived(List<EMMessage> list) {
//        for (final EMMessage message : list) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    message.setMsgTime(System.currentTimeMillis());
//                    EMTextMessageBody emtextmessage = (EMTextMessageBody) message.getBody();
//                    ChatMessage chatMessage = new ChatMessage();
//                    chatMessage.setContent(emtextmessage.getMessage());
//                    chatMessage.setIsMeSend(0);
//                    chatMessage.setIsRead(1);
//                    chatMessage.setTime(System.currentTimeMillis() + "");
//                    chatMessageList.add(chatMessage);
//                    initChatMsgListView();
//                }
//            });
//        }
//    }
//
//    @Override
//    public void onCmdMessageReceived(List<EMMessage> list) {
//
//    }
//
//    @Override
//    public void onMessageRead(List<EMMessage> list) {
//
//    }
//
//    @Override
//    public void onMessageDelivered(List<EMMessage> list) {
//
//    }
//
//    @Override
//    public void onMessageRecalled(List<EMMessage> list) {
//
//    }
//
//    @Override
//    public void onMessageChanged(EMMessage emMessage, Object o) {
//
//    }
//
//
//    protected void onDestroy() {
//        //在不需要的时候移除listener，如在activity的onDestroy()时
//        super.onDestroy();
//        EMClient.getInstance().chatManager().removeMessageListener(mMessageListener);
//    }
}
